package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDto;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Ronaldo
 * @date 2021/8/1
 */
@Service
@Transactional
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper,WmUser> implements WmUserService {


    @Override
    public ResponseResult login(WmUserDto wmUserDto) {

        //查询用户信息
        WmUser user = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, wmUserDto.getName()));

        //判断用户存在与否
        if (Objects.isNull(user)){
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_USER_INFO);
        }

        //校验密码
        String inputPassword = wmUserDto.getPassword();
        String dbPassword = user.getPassword();
        boolean flag = BCrypt.checkpw(inputPassword, dbPassword);
        if (!flag){
            throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        Map<String,Object> resultMap = new HashMap<>(16);
        //获取token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        resultMap.put("token",token);
        user.setPassword("");
        resultMap.put("user",user);

        WmUser wmUser = new WmUser();
        wmUser.setId(user.getId());
        wmUser.setLoginTime(new Date());
        updateById(wmUser);

        return ResponseResult.okResult(resultMap);
    }
}
